// 配置文件 公共方法
import Vue from 'vue'

const baseUrl = 'https://love.soft.haoyangsoft.com'
const imgUrl = 'https://love.soft.haoyangsoft.com/wxapp/images/'
//提示
const tipMsg =(title,icon,time,mask)=>{
        title = title == undefined ? "系统繁忙" : title;
        icon = icon == undefined ? "none" : icon;
        time = time == undefined ? 1500 : time;
        mask = mask == undefined ? true : mask;
        uni.showToast({
            title:title,
            icon:icon,
            mask:mask,
            duration:time
        })
}
// 设置title
const setTitle = title =>{
	//如果需要在页面进入时设置标题，可以在onReady内执行，以避免被框架内的修改所覆盖
	//如果必须在onShow内执行需要延迟一小段时间
	uni.setNavigationBarTitle({
	    title: title
	})
}

//验证手机号
const checkPhone = phone=>{
    if(!(/^1[23456789]\d{9}$/.test(phone))){
        uni.showToast({
            title:"手机号格式不正确",
            icon:'none'
        })
        return false;
    }
    return true;
}

// 验证码邮箱
const checkEmail = email=>{
	if(!(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email))){
		uni.showToast({
		    title:"邮箱格式不正确",
		    icon:'none'
		})
		return false;
	}
	return true;
}

// 页面跳转
const jump = (url,clear)=>{
	console.log(url)
	clear ? 
	uni.reLaunch({
		url: url
	})
	:
	uni.navigateTo({
	    url: url
	})
}


const nowDate = ()=>{
	let date = new Date();
	let seperator1 = "-";
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	let currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate
}

const nowTime = ()=>{
	let date = new Date();
	let seperator1 = ":";
	let hours = date.getHours();
	let min = date.getMinutes();
	if (hours >= 0 && hours <= 9) {
		hours = "0" + hours;
	}
	if (min >= 0 && min <= 9) {
		min = "0" + min;
	}
	return hours + seperator1 + min
}

const back = (delta) =>{
	uni.navigateBack({
		delta:delta || 1
	})
}


const upload = (url,option = {})=>{
	return new Promise((resolve,reject)=>{
		uni.showLoading({
			title:'上传中...',
			mask:!0
		})
		uni.uploadFile({
			url:baseUrl + url,
			name:option.name || 'file',
			filePath:option.filePath,
			formData:option.formData,
			header:option.header,
			success(res){
				uni.hideLoading()
				if(res.statusCode == 200){
					let data = JSON.parse(res.data)
					if(data.code == 1){
						resolve(data.data.value)
					}
				}else{
					reject(res)
				}
			},
			fail(err) {
				uni.hideLoading()
				reject(err)
			}
		})
	})
}

const uploadVideo = (url,option = {})=>{
	return new Promise((resolve,reject)=>{
		uni.showLoading({
			title:'上传中...',
			mask:!0
		})
		uni.uploadFile({
			url:baseUrl + url,
			name:option.name || 'file',
			filePath:option.filePath,
			formData:option.formData,
			header:option.header,
			success(res){
				//console.log(res)
				uni.hideLoading()
				if(res.statusCode == 200){
					let data = JSON.parse(res.data)
					if(data.code == 200){
						resolve(data.data[0])
					}
				}else{
					reject(res)
				}
			},
			fail(err) {
				uni.hideLoading()
				reject(err)
			}
		})
	})
}

const getCode = ()=>{
	if (document.URL.match(/\?.*#/)) {
	    let temp = document.URL.match(/\?.*#/)[0]
	    if (temp.match(/=.*&/)) {
	      // 解析Code
	      let code = temp.match(/=.*&/)[0]
	      code = code.substr(1, code.length) // 去掉 ?
	      code = code.substr(0, code.length - 1)  // 去掉 #
	      // 重置URL(去掉code参数，避免重复调用)
	      window.history.pushState({}, 0, document.URL.replace(temp.substr(0, temp.length - 1), ''))
		  return code
	    }
		return false
	}
	return false
}

const getParams = (key)=>{
	const params = {}
	window.location.hash.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>params[k]=v)
	return key ? params[key] : params
}


const cookie = {
	set: function(name, value){
	  // 缓存过期时间
	  let Days = 30
	  let exp = new Date()
	  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
	  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
	},
	get: function(name){
	  let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
	  let reg = arr
	  arr = document.cookie.match(reg)
	  if (arr) {
	    return unescape(arr[2])
	  }else{
	    return null
	  }
	},
	del: function(name){
	  let exp = new Date()
	  exp.setTime(exp.getTime() - 1)
	  let cval = this.cookie.get(name)
	  if (cval != null) {
	    document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
	  }
	}
}

const h5Copy = (content)=>{
	if (!document.queryCommandSupported('copy')) {
		// 不支持
		return false
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	textarea.remove()
	return result
}

const agree = (text)=>{
	tipMsg(text || '请先阅读并同意协议')
}

// 全局混入
const mixin = {
	methods:{
		jump(url,type){
			this.$app.jump(url,type)
		}
	}
}



const math = {
	// 加法精度
	add:function(...val){
		let max = 0
		let count = 0
		for (let i = 0; i < val.length; i++) {
		  const strVal = val[i].toString()
		  const index = strVal.indexOf('.')
		  let num = 0
		  if (index > -1) {
		    num = strVal.length - 1 - index
		    max = num > max ? num : max
		  }
		}
		for (let i = 0; i < val.length; i++) {
		  count += Math.round(val[i] * Math.pow(10, max))
		}
		return count / Math.pow(10, max)
	},
	sub:function(...val) {
		let max = 0
		let count = val[0] | 0
		for (let i = 0; i < val.length; i++) {
			const strVal = val[i].toString()
			const index = strVal.indexOf('.')
			let num = 0
			if (index > -1) {
				num = strVal.length - 1 - index
				max = num > max ? num : max
			}
		}
		for (let i = 0; i < val.length; i++) {
			if(i==0) {
				count = Math.round(val[i] * Math.pow(10, max))
			}else{
				count -= Math.round(val[i] * Math.pow(10, max))
			}
		}
		return count / Math.pow(10, max)
	},
	ride:function(...val) {
		const strVal = val[0].toString()
		const strValTwo = val[1].toString()
		const index = strVal.indexOf('.')
		const indexTwo = strValTwo.indexOf('.')
		const num = [0, 0]
		if (index > -1) {
			num[0] = strVal.length - 1 - index
		}
		if (indexTwo > -1) {
			num[1] = strValTwo.length - 1 - index
		}
		return Math.round((val[0] * Math.pow(10, num[0])) * (val[1] * Math.pow(10, num[1]))) / Math.pow(10, num[0] + num[1])
	},
	exc(val, valTwo = 100) {
		const strVal = val.toString()
		const strValTwo = valTwo.toString()
		const index = strVal.indexOf('.')
		const indexTwo = strValTwo.indexOf('.')
		const num = [0, 0]
		if (index > -1) {
			num[0] = strVal.length - 1 - index
		}
		if (indexTwo > -1) {
			num[1] = strValTwo.length - 1 - index
		}
		return Math.round(val * Math.pow(10, num[0])) / (Math.round((valTwo * Math.pow(10, num[1]))) * Math.pow(10, num[0] - num[1]))
	}
}

const bu0 = (num)=> parseInt(num) >= 10 ? num : '0' + num

const bigNumberTransform = (value)=>{
  const newValue = ['', '', '']
  let fr = 1000
  let num = 3
  let text1 = ''
  let fm = 1
  while (value / fr >= 1) {
    fr *= 10
    num += 1
    // console.log('数字', value / fr, 'num:', num)
  }
  if (num <= 4) { // 千
    newValue[0] = parseInt(value / 1000) + ''
    newValue[1] = '千'
  } else if (num <= 8) { // 万
    text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万'
    // tslint:disable-next-line:no-shadowed-variable
    fm = text1 === '万' ? 10000 : 10000000
    if (value % fm === 0) {
      newValue[0] = parseInt(value / fm) + ''
    } else {
      newValue[0] = parseFloat(value / fm).toFixed(1) + ''
    }
    newValue[1] = text1
  } else if (num <= 16) { // 亿
    text1 = (num - 8) / 3 > 1 ? '千亿' : '亿'
    text1 = (num - 8) / 4 > 1 ? '万亿' : text1
    text1 = (num - 8) / 7 > 1 ? '千万亿' : text1
    // tslint:disable-next-line:no-shadowed-variable
    fm = 1
    if (text1 === '亿') {
      fm = 100000000
    } else if (text1 === '千亿') {
      fm = 100000000000
    } else if (text1 === '万亿') {
      fm = 1000000000000
    } else if (text1 === '千万亿') {
      fm = 1000000000000000
    }
    if (value % fm === 0) {
      newValue[0] = parseInt(value / fm) + ''
    } else {
      newValue[0] = parseFloat(value / fm).toFixed(2) + ''
    }
    newValue[1] = text1
  }
  if (value < 1000) {
    newValue[0] = value + ''
    newValue[1] = ''
  }
  return newValue.join('')
}


module.exports = {
	tipMsg,
	checkPhone,
	checkEmail,
	jump,
	setTitle,
	nowDate,
	nowTime,
	back,
	imgUrl,
	baseUrl,
	upload,
	getCode,
	getParams,
	cookie,
	h5Copy,
	agree,//协议提示
	mixin,
	math,
	bu0,
	uploadVideo,
	bigNumberTransform
}